package io.zhile.research.intellij.ier.listener;

import com.intellij.ide.AppLifecycleListener;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import io.zhile.research.intellij.ier.common.Resetter;
import io.zhile.research.intellij.ier.helper.BrokenPlugins;
import io.zhile.research.intellij.ier.helper.Constants;
import io.zhile.research.intellij.ier.helper.ResetTimeHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * 应用生命周期监听器
 */
public class AppEventListener implements AppLifecycleListener {

    public void appFrameCreated(String[] commandLineArgs, @NotNull Ref<Boolean> willOpenProject) {

    }

    /**
     * app启动的时候
     * @param projectFromCommandLine
     */
    public void appStarting(@Nullable Project projectFromCommandLine) {
        //启动需要 生成ResetAction 类
        ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
            @Override
            public void run() {
                ActionManager.getInstance().getAction(Constants.RESET_ACTION_ID);
            }
        });
    }

    public void projectFrameClosed() {

    }

    public void projectOpenFailed() {

    }

    public void welcomeScreenDisplayed() {

    }

    /**
     * 在 idea 关闭的时候触发
     */
    public void appClosing() {
        //清除 BrokenPlugins 文件
        BrokenPlugins.fix();

        //如果没有设置自动重置, 则直接结束
        if (!Resetter.isAutoReset()) {
            return;
        }

        //设置了自动重置, 就进行重置一下, 并更新最新的重置时间
        Resetter.reset(Resetter.getEvalRecords());
        ResetTimeHelper.resetLastResetTime();
    }
}
